import { createRouter, createWebHistory } from 'vue-router'
import newMobileRoutes from './new-routes'
import store from '@/store'

// 系统级路由
const systemRoutes = [
  {
    path: '/',
    redirect: '/new/home'
  },
  {
    path: '/success',
    name: 'Success',
    component: () => import('../views/system/ResultSuccess.vue')
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('../views/system/NotFound.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: { name: 'NotFound' }
  }
]

// 合并路由
const allRoutes = [
  ...systemRoutes,
  ...newMobileRoutes
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: allRoutes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - H+移动工作平台`
  }
  
  // 在这里可以添加登录验证等逻辑
  
  next()
})

// 全局后置钩子
router.afterEach((to) => {
  // 对于新版移动端页面，记录访问历史
  if (to.path.startsWith('/new') && to.name) {
    // 在Vue 3中，不能直接通过router.app.$store访问store
    // 而是通过导入store实例来使用
    if (store) {
      // 获取路由元数据中的图标信息
      const icon = to.meta.icon || getDefaultIcon(to.path)
      const iconBg = to.meta.iconBg || getDefaultIconBg(to.path)
      
      // 记录访问历史
      store.dispatch('mobile/recordVisit', {
        path: to.path,
        name: to.meta.title || to.name,
        time: new Date().toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric', 
          hour: 'numeric',
          minute: 'numeric'
        }),
        icon,
        iconBg
      })
    }
  }
})

// 获取默认图标
function getDefaultIcon(path) {
  if (path.includes('/finance')) return 'balance-o'
  if (path.includes('/material')) return 'shopping-cart-o'
  if (path.includes('/asset')) return 'desktop-o'
  if (path.includes('/profile')) return 'user-o'
  return 'apps-o'
}

// 获取默认颜色
function getDefaultIconBg(path) {
  if (path.includes('/finance')) return 'blue'
  if (path.includes('/material')) return 'green'
  if (path.includes('/asset')) return 'purple'
  if (path.includes('/profile')) return 'orange'
  return 'cyan'
}

export default router 